"""
@FileName：video_player.py\n
@Description：\n
@Author：锦沐Python\n
@Time：2024/8/16 14:40\n
"""

import cv2
from PIL import Image, ImageTk


class VideoPlayer:
    """
   播放视频
    """
    def __init__(self, canvas, video_source):
        self.canvas = canvas
        # 图片对象
        self.photo = None
        # 视频解析对象
        self.vid = cv2.VideoCapture(video_source)
        # 播放状态
        self.is_playing = False
        # 当前帧数
        self.current_frame = 0
        # 总帧数
        self.all_frame = int(self.vid.get(cv2.CAP_PROP_FRAME_COUNT))

    def update(self):
        """
        更新页面
        """
        if self.is_playing:
            ret, frame = self.vid.read()
            if ret:
                self.current_frame += 1
                frame = cv2.resize(frame, (self.canvas.winfo_width(), self.canvas.winfo_height()))
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                self.photo = ImageTk.PhotoImage(image=Image.fromarray(frame))
                # 只更新图像，不清除整个画布
                self.canvas.create_image(0, 0, image=self.photo, anchor="nw")

    def play(self):
        """
        开始播放
        """
        self.is_playing = True

    def pause(self):
        """
        暂停播放
        """
        self.is_playing = False

    def resume(self):
        """
        继续播放
        """
        self.is_playing = True

    def close(self):
        """
        关闭
        """
        self.pause()
        self.vid.release()

    def get_current_progress(self):
        """
        通过 百分比 计算当前进度
        :return:
        """
        try:
            percent = (self.current_frame / self.all_frame) * 100
            return percent
        except ZeroDivisionError as e:
            print(f"视频打开错误：{e}")

    def set_start(self, percent):
        """
        根据百分比，将视频位置设置为指定的帧数
        :param percent: 百分比 0 - 1
        """
        # print(self.all_frame)
        start_time = int(self.all_frame * percent)
        print(start_time)
        self.vid.set(cv2.CAP_PROP_POS_FRAMES, start_time)
        self.current_frame = start_time
